<template>
  <div ref="chartDom" :style="{ height: height }"></div>
</template>

<script>
import echarts from 'echarts'
import 'echarts/lib/chart/line'
import 'echarts/lib/chart/bar'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/legend'
import 'echarts/lib/component/grid'
import resize from './mixins/resize'

export default {
  name: 'Chart',
  mixins: [resize],
  props: {
    type: {
      type: String,
      default: 'line',
      validator: function(value) {
        return ['line', 'bar'].indexOf(value) !== -1
      }
    },
    data: {
      type: Object,
      required: true,
      default: () => ({ xAxis: [], series: [] })
    },
    height: {
      type: String,
      default: '400px'
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    data: {
      deep: true,
      handler() {
        this.initChart()
      }
    },
    type() {
      this.initChart()
    }
  },
  mounted() {
    this.initChart()
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
  },
  methods: {
    initChart() {
      if (!this.$refs.chartDom) return

      this.chart = echarts.init(this.$refs.chartDom)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.data.xAxis,
          axisLabel: {
            interval: 0,
            rotate: this.data.xAxis.length > 6 ? 30 : 0
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: '数据量',
          type: this.type,
          data: this.data.series,
          barWidth: this.type === 'bar' ? '40%' : null,
          smooth: this.type === 'line',
          itemStyle: {
            color: '#409EFF'
          },
          areaStyle: this.type === 'line' ? {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ])
          } : null
        }]
      }

      this.chart.setOption(option)
      this.chart.on('click', params => {
        this.$emit('chart-click', params)
      })
    }
  }
}
</script>

<style scoped>
/* 保留必要的样式 */
</style>
